<?php

namespace App\Exports;

use App\Models\FrontendUser;
use Carbon\Carbon;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;

class FrontendExport implements FromQuery, WithMapping, WithHeadings
{
    public $data;
    public $request;

    public function __construct($data)
    {
        $this->data = $data;
        $this->request = json_decode($this->data->request, true);
    }

    public function query()
    {
        $query = FrontendUser::query()
            ->with(['auth', 'channel', 'parent'])
            ->when(!empty($this->request['keyword']), function ($q) {
                $likeVal = '%' . $this->request['keyword'] . '%';

                return $q->where('nickname', 'like', $likeVal)->orWhere('mobile', 'like', $likeVal);
            })
            ->when(!empty($this->request['start_date']), function ($q) {
                $startTime = Carbon::parse($this->request['start_date'])->startOfDay();

                return $q->where('created_at', '>=', $startTime);
            })
            ->when(!empty($this->request['end_date']), function ($q) {
                $endTime = Carbon::parse($this->request['end_date'])->endOfDay();

                return $q->where('created_at', '<=', $endTime);
            })->when(!empty($this->request['real_name']), function ($q) {
                if (1 == $this->request['real_name']) {
                    return $q->has('auth');
                }

                return $q->doesntHave('auth');
            });

        if (!empty($this->request['agent_id'])) {
            $query = $query->where('agent_id', $this->request['agent_id']);
        }

        if (!empty($this->data['agent_id'])) {
            $query = $query->where('agent_id', $this->data['agent_id']);
        }

        return $query->orderByDesc('id');
    }

    public function headings(): array
    {
        return [
            'ID',
            '昵称',
            '真实姓名',
            '身份证号',
            '手机号',
            '邀请人',
            '注册渠道',
            '注册时间',
            '上次登录时间',
        ];
    }

    public function map($user): array
    {
        /* @var $user FrontendUser */
        return [
            $user->id,
            drop_special_char($user->nickname),
            $user->auth ? $user->auth->real_name : '-',
            $user->auth ? (' ' . $user->auth->id_card) : '-',
            ' ' . $user->mobile,
            $user->parent ? (' ' . $user->parent->mobile) : '-',
            $user->channel ? (' ' . $user->channel->name) : '-',
            $user->created_at,
            $user->last_login_time,
        ];
    }
}
